<template>
    <div class="app-container">
        <el-row :gutter="20">
            <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
                <!--分类数据-->
                <pane size="16">
                    <el-col>
                        <div class="head-container">
                            <el-input v-model="deptName" style="max-width: 600px" placeholder="请输入名称"
                                class="input-with-select">
                                <template #append>
                                    <el-button icon="Plus" @click="addTopLevel" v-hasPermi="['product:add']"/>
                                </template>
                            </el-input>
                        </div>
                        <div class="head-container">
                            <el-tree class="custom-tree-style" :data="deptOptions"
                                :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false"
                                :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current
                                default-expand-all @node-click="handleNodeClick"
                                @node-contextmenu="handleNodeContextmenu">
                                <template #default="{ node, data }">
                                    <span class="custom-tree-node">
                                        <span>{{ node.label }}</span>
                                        <img src="@/assets/images/profile.jpg"
                                            style="height:16px; margin-left:8px; vertical-align:text-bottom" alt="节点图标"
                                            @click="handleImagePreview" />
                                    </span>
                                </template>
                            </el-tree>
                        </div>
                    </el-col>
                </pane>
                <!--用户数据-->
                <pane size="84">
                    <el-col>
                        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch"
                            label-width="68px">
                            <el-form-item label="产品名称" prop="userName">
                                <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable
                                    style="width: 240px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="手机号码" prop="phonenumber">
                                <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable
                                    style="width: 240px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="状态" prop="status">
                                <el-select v-model="queryParams.status" placeholder="用户状态" clearable
                                    style="width: 240px">
                                    <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="创建时间" style="width: 308px">
                                <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange"
                                    range-separator="-" start-placeholder="开始日期"
                                    end-placeholder="结束日期"></el-date-picker>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                            </el-form-item>
                        </el-form>

                        <el-row :gutter="10" class="mb8">
                            <el-col :span="1.5">
                                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                                    v-hasPermi="['product:add']">新增</el-button>
                            </el-col>

                            <el-col :span="1.5">
                                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                                    v-hasPermi="['product:remove']">删除</el-button>
                            </el-col>

                            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"
                                :columns="columns"></right-toolbar>
                        </el-row>

                        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="50" align="center" />
                            <el-table-column width="80" label="产品序号" align="center" key="userId" prop="productId" />
                            <el-table-column label="产品名称" align="center" key="name" prop="name"
                                :show-overflow-tooltip="true" />
                            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
                                <template #default="scope">
                                    <span>{{ parseTime(scope.row.createTime) }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" align="center" width="500"
                                class-name="small-padding fixed-width">
                                <template #default="scope">
                                    <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                                            v-hasPermi="['product:edit']"></el-button>
                                    </el-tooltip>
                                    <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                                            v-hasPermi="['product:remove']"></el-button>
                                    </el-tooltip>
                                    <el-tooltip content="上传附件" placement="top" v-if="scope.row.userId !== 1">
                                        <el-button link type="primary" icon="Upload"
                                            @click="uploadProductFile(scope.row)"
                                            v-hasPermi="['product:upload']"></el-button>
                                    </el-tooltip>
                                    <el-tooltip content="查看附件" placement="top">
                                        <el-button link type="primary" icon="Search" @click="queryFile(scope.row)"
                                            v-hasPermi="['product:info']"></el-button>
                                    </el-tooltip>
                                </template>
                            </el-table-column>
                        </el-table>
                        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                            v-model:limit="queryParams.pageSize" @pagination="getList" />
                    </el-col>
                </pane>
            </splitpanes>
        </el-row>

        <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="产品名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入产品名称" maxlength="30" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="产品描述">
                            <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!--产品详情-->
        <el-dialog title="产品详情" v-model="infOpen" width="600px" append-to-body>
            <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="产品名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入产品名称" maxlength="30" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="产品描述">
                            <el-input v-model="form.description" type="textarea" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <div v-show="contextMenuVisible" class="context-menu"
            :style="{ left: contextMenuLeft + 'px', top: contextMenuTop + 'px' }">
            <div class="menu-item" @click="addSubNode" v-if="currentNode?.data?.level !== 1" v-hasPermi="['product:add']">
                增加下级节点
            </div>
            <div class="menu-item" @click="uploadFile" v-if="currentNode?.data?.level !== 1" v-hasPermi="['product:upload']">
                上传文件
            </div>
            <div class="menu-item" @click="renameNode"  v-hasPermi="['product:edit']">修改名称</div>
            <div class="menu-item danger" @click="deleteNode" v-if="!currentNode?.data?.children?.length" v-hasPermi="['product:remove']">
                删除节点
            </div>
        </div>
        <el-image-viewer v-if="imageViewerVisible" :url-list="previewImgList" :initial-index="previewIndex"
            @close="imageViewerVisible = false" />
        <el-dialog :title="uploadProduct.title" v-model="uploadProduct.open" width="50%" append-to-body>
            <div>
                <div style="margin-bottom: 15px;font-size: 20px;color:red;">当前产品：{{ uploadProduct.productName }}</div>
                <div style="margin-bottom: 15px;font-size: 20px;color:red;">
                    <div style="display: flex;">
                        <span>请选择分类：</span>
                        <el-select v-model="productType" placeholder="请选择">
                            <el-option v-for="dict in sys_product_type" :key="dict.value" :label="dict.label"
                                :value="dict.value"></el-option>
                        </el-select>
                    </div>

                </div>

                <el-upload ref="uploadRef" :limit="50" :headers="uploadProduct.headers"
                    :action="uploadProduct.url + '?productId=' + uploadProduct.productId + '&productType=' + productType"
                    :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag
                    multiple>
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <template #tip>
                        <div class="el-upload__tip text-center">
                            <span>仅允许上传docx,xlsx,fbx,jpg,png,mp4格式文件</span>
                        </div>
                    </template>
                </el-upload>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm" :disabled="!uploadProduct.productId">确
                        定</el-button>
                    <el-button @click="uploadProduct.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog title="产品附件" v-model="productInfoOpen" width="80%" append-to-body style="max-height: 800px; height: 800px;overflow:auto;">
            <div>
                <el-row>
                    <el-col :span="18">
                        <el-row>
                            <el-col :span="24">
                                <el-descriptions title="基础信息" :column="1" :size="size" border>
                                    <!-- <template #extra>
                                        <el-button type="primary">下载资料</el-button>
                                    </template> -->
                                    <el-descriptions-item :width="60">
                                        <template #label>
                                            <div class="cell-item">
                                                <el-icon :style="iconStyle">
                                                    <user />
                                                </el-icon>
                                                产品名称
                                            </div>
                                        </template>
                                        {{ productInfo.name }}
                                    </el-descriptions-item>
                                    <el-descriptions-item>
                                        <template #label>
                                            <div class="cell-item">
                                                <el-icon :style="iconStyle">
                                                    <user />
                                                </el-icon>
                                                产品描述
                                            </div>
                                        </template>
                                        {{ productInfo.description }}
                                    </el-descriptions-item>
                                </el-descriptions>
                            </el-col>
                        </el-row>
                        <el-row :gutter="10" class="mb8" style="margin-top: 20px;">
                            <el-col :span="1.5">
                                <el-button type="danger" plain icon="Delete" :disabled="delDisabled" @click="delFile" v-hasPermi="['product:remove']"
                                    size="small">删除</el-button>
                            </el-col>
                        </el-row>
                        <!--附件-->
                        <el-row>
                            <el-col :span="24">
                                <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                                    <el-tab-pane label="产品实物图" name="images">
                                        <el-row>
                                            <el-col :span="4"
                                                v-for="(item, index) in productInfo.fileCategories?.images"
                                                :key="index + '_img'" class="card-item">
                                                <div>
                                                    <el-image :src="item.fileUrl" :initial-index="previewIndex"
                                                        @click="handleImagePreview(index)" :fit="contain"
                                                        style="width: 100px; height:100px;">
                                                        <template #error>
                                                            <div class="image-slot">加载失败</div>
                                                        </template>
                                                    </el-image>
                                                </div>
                                                <div class="card-check">
                                                    <div>
                                                        <el-checkbox v-model="selectedImages" :label="item.fileName"
                                                            @change="handleCheckboxChange" style="margin-right:5px;">
                                                            <el-tooltip :content="item.fileName" placement="top">
                                                                <span>{{
            item.fileName.length > 15 ?
                item.fileName.slice(0, 15) + '...' :
                item.fileName
        }}</span>
                                                            </el-tooltip>
                                                        </el-checkbox>
                                                    </div>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                    <el-tab-pane label="产品效果图" name="effectDrawing">
                                        <el-row>
                                            <el-col :span="4"
                                                v-for="(item, index) in productInfo.fileCategories?.effectDrawing"
                                                :key="index + '_effect'" class="card-item">
                                                <div>
                                                    <el-image :src="item.fileUrl" :initial-index="previewIndex"
                                                        @click="handleImagePreview(index)" :fit="contain"
                                                        style="width: 100px; height:100px;">
                                                        <template #error>
                                                            <div class="image-slot">加载失败</div>
                                                        </template>
                                                    </el-image>
                                                </div>
                                                <div class="card-check">
                                                    <div>
                                                        <el-checkbox v-model="selectedImages" :label="item.fileName"
                                                            @change="handleCheckboxChange" style="margin-right:5px;">
                                                            <el-tooltip :content="item.fileName" placement="top">
                                                                <span>{{
            item.fileName.length > 15 ?
                item.fileName.slice(0, 15) + '...' :
                item.fileName
        }}</span>
                                                            </el-tooltip>
                                                        </el-checkbox>
                                                    </div>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                    <el-tab-pane label="产品模型MAX格式" name="max">
                                        <el-row>
                                            <el-col :span="24" v-for="(item, index) in productInfo.fileCategories?.max"
                                                :key="index + '_max'" style="margin:10px;">
                                                <el-link type="primary" :href="item.fileUrl" :download="item.fileName">
                                                    <div
                                                        style="margin-top:8px; text-align:center;display: flex;justify-content: center;align-items: center">
                                                        <div>
                                                            <el-checkbox v-model="selectedImages"
                                                                @change="handleCheckboxChange" :label="item.fileName"
                                                                style="margin-right:5px;">
                                                                <el-tooltip :content="item.fileName" placement="top">
                                                                    <span>{{
            item.fileName.length > 15 ?
                item.fileName.slice(0, 15) + '...' :
                item.fileName
        }}</span>
                                                                </el-tooltip>
                                                            </el-checkbox>
                                                        </div>
                                                    </div>
                                                </el-link>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                    <el-tab-pane label="产品模型step格式" name="step">
                                        <el-row>
                                            <el-col :span="24" v-for="(item, index) in productInfo.fileCategories?.step"
                                                :key="index + '_step'" style="margin:10px;">
                                                <el-link type="primary" :href="item.fileUrl" :download="item.fileName">
                                                    <div
                                                        style="margin-top:8px; text-align:center;display: flex;justify-content: center;align-items: center">
                                                        <div>
                                                            <el-checkbox v-model="selectedImages"
                                                                @change="handleCheckboxChange" :label="item.fileName"
                                                                style="margin-right:5px;">
                                                                <el-tooltip :content="item.fileName" placement="top">
                                                                    <span>{{
            item.fileName.length > 15 ?
                item.fileName.slice(0, 15) + '...' :
                item.fileName
        }}</span>
                                                                </el-tooltip>
                                                            </el-checkbox>
                                                        </div>
                                                    </div>
                                                </el-link>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                    <el-tab-pane label="产品说明书" name="specification">
                                        <el-row>
                                            <el-col :span="24"
                                                v-for="(item, index) in productInfo.fileCategories?.specification"
                                                :key="index + '_specification'" style="margin:10px;">
                                                <el-link type="primary" :href="item.fileUrl" :download="item.fileName">
                                                    <div
                                                        style="margin-top:8px; text-align:center;display: flex;justify-content: center;align-items: center">
                                                        <div>
                                                            <el-checkbox v-model="selectedImages"
                                                                @change="handleCheckboxChange" :label="item.fileName"
                                                                style="margin-right:5px;">
                                                                <el-tooltip :content="item.fileName" placement="top">
                                                                    <span>{{
            item.fileName.length > 15 ?
                item.fileName.slice(0, 15) + '...' :
                item.fileName
        }}</span>
                                                                </el-tooltip>
                                                            </el-checkbox>
                                                        </div>
                                                    </div>
                                                </el-link>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                    <el-tab-pane label="产品配置参数表" name="config">
                                        <el-row>
                                            <el-col :span="24"
                                                v-for="(item, index) in productInfo.fileCategories?.config"
                                                :key="index + '_config'" style="margin:10px;">
                                                <el-link type="primary" :href="item.fileUrl" :download="item.fileName">
                                                    <div
                                                        style="margin-top:8px; text-align:center;display: flex;justify-content: center;align-items: center">
                                                        <div>
                                                            <el-checkbox v-model="selectedImages"
                                                                @change="handleCheckboxChange" :label="item.fileName"
                                                                style="margin-right:5px;">
                                                                <el-tooltip :content="item.fileName" placement="top">
                                                                    <span>{{
            item.fileName.length > 15 ?
                item.fileName.slice(0, 15) + '...' :
                item.fileName
        }}</span>
                                                                </el-tooltip>
                                                            </el-checkbox>
                                                        </div>
                                                    </div>
                                                </el-link>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                    <el-tab-pane label="产品宣传视频" name="promotionalVideo">
                                        <el-row>
                                            <el-col :span="24"
                                                v-for="(item, index) in productInfo.fileCategories?.promotionalVideo"
                                                :key="index + '_promotionalVideo'" style="margin:10px;">
                                                <el-link type="primary" :href="item.fileUrl" :download="item.fileName">
                                                    <div
                                                        style="margin-top:8px; text-align:center;display: flex;justify-content: center;align-items: center">
                                                        <div>
                                                            <el-checkbox v-model="selectedImages"
                                                                @change="handleCheckboxChange" :label="item.fileName"
                                                                style="margin-right:5px;">
                                                                <el-tooltip :content="item.fileName" placement="top">
                                                                    <span>{{
                                                                        item.fileName.length > 15 ?
                                                                        item.fileName.slice(0, 15) + '...' :
                                                                        item.fileName
                                                                        }}</span>
                                                                </el-tooltip>
                                                            </el-checkbox>
                                                        </div>
                                                    </div>
                                                </el-link>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                    <el-tab-pane label="产品操作演示视频" name="demonstrationVideo">
                                        <el-row>
                                            <el-col :span="24"
                                                v-for="(item, index) in productInfo.fileCategories?.demonstrationVideo"
                                                :key="index + '_demonstrationVideo'" style="margin:10px;">
                                                <el-link type="primary" :href="item.fileUrl" :download="item.fileName">
                                                    <div
                                                        style="margin-top:8px; text-align:center;display: flex;justify-content: center;align-items: center">
                                                        <div>
                                                            <el-checkbox v-model="selectedImages"
                                                                @change="handleCheckboxChange" :label="item.fileName"
                                                                style="margin-right:5px;">
                                                                <el-tooltip :content="item.fileName" placement="top">
                                                                    <span>{{
                                                                        item.fileName.length > 15 ?
                                                                        item.fileName.slice(0, 15) + '...' :
                                                                        item.fileName
                                                                        }}</span>
                                                                </el-tooltip>
                                                            </el-checkbox>
                                                        </div>
                                                    </div>
                                                </el-link>
                                            </el-col>
                                        </el-row>
                                    </el-tab-pane>
                                </el-tabs>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="6" style="max-height:800px; overflow: auto">
                        <el-row>
                            <el-col :span="24" style="margin-top: 5px;padding: 5px;">
                                <el-button type="primary" @click="handleShare" :disabled="selectedImages.length === 0"  v-hasPermi="['product:share']">
                                    分享选中项（{{ selectedImages.length }}）
                                </el-button>
                                <!-- 分类展示选中文件 -->
                                <div v-if="selectedImages.length > 0" style="margin-top: 15px;">
                                    <div style="border: 1px solid #ebeef5; border-radius: 4px;padding: 10px;">
                                        <el-collapse v-model="activeCollapseNames">
                                            <el-collapse-item v-for="(files, category) in selectedFilesByCategory"
                                                :key="category" :title="categoryMap[category] + ` (${files.length}个文件)`"
                                                :name="category">
                                                <div v-for="file in files" :key="file.fileName" style="line-height: 24px; padding: 5px 15px;
                                                   border-bottom: 1px dashed #eee;">
                                                    {{ file.fileName }}（.{{ file.fileType }}）
                                                </div>
                                            </el-collapse-item>
                                        </el-collapse>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
        <el-dialog v-model="showShareTable" title="分享链接" width="70%">
            <!-- 新增访问信息区域 -->
            <div v-if="shareUrl" class="share-access" style="margin-top: 20px; padding: 15px; background: #f5f7fa;">
                <el-row :gutter="20">
                    <el-col :span="20">
                        <div class="mt-4">
                            <el-input v-model="shareUrl" style="max-width: 600px" placeholder="Please input"
                                class="input-with-select">
                                <template #append>
                                    <el-button :icon="Share" @click="handleCopy" />
                                </template>
                            </el-input>
                        </div>
                    </el-col>
                    <el-col :span="20">
                        <div style="margin-top: 20px;margin-bottom: 20px;">
                            <el-link type="primary" @click="handleDownloadQr">点击二维码下载进行分享</el-link>
                        </div>
                        <div class="qr-code-container">
                            <vue-qrcode :key="shareUrl" :value="shareUrl" :width="600" ref="qrcode" />
                        </div>
                    </el-col>
                </el-row>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="showShareTable = false">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="User">
import { computed, ref } from 'vue'
import VueQrcode from '@chenfengyuan/vue-qrcode';
import { getToken } from "@/utils/auth";
import {
    Iphone,
    Location,
    OfficeBuilding,
    Tickets,
    User,
    Document, Picture, Share
} from '@element-plus/icons-vue'
import { ElNotification, ElMessageBox, ElMessage, ElImageViewer } from 'element-plus'
import useAppStore from '@/store/modules/app'
import {
    listCategories, listCategoriesExcludeChild, getCategories, addCategories, updateCategories, delCategories, categoryTreeSelect
    , addProducts, listProducts, updateProducts, delProducts, getProducts, addProductsShare, delProductFiles
} from '@/api/products/index'
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
const router = useRouter();
const appStore = useAppStore()
const { proxy } = getCurrentInstance();
const { sys_product_type } = proxy.useDict("sys_product_type");

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const productInfoOpen = ref(false);
const enabledDeptOptions = ref(undefined);
const productInfo = ref({})
const activeName = ref('images');
const productType = ref('images');
// 新增折叠面板激活状态
const activeCollapseNames = ref([]);
const showShareTable = ref(false); // 分享对话框
const shareUrl = ref('https://product.abzykj.cn/');
const delDisabled = ref(true);
const currentProductId = ref(0);
/*************文件分享功能************************************/
/** 下载二维码 */
const handleDownloadQr = () => {
    const svgElement = document.querySelector('.qr-code-container svg');
    if (!svgElement) {
        ElMessage.error('未找到二维码');
        return;
    }

    const svgData = new XMLSerializer().serializeToString(svgElement);
    const blob = new Blob([svgData], { type: "image/svg+xml;charset=utf-8" });
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = url;
    link.download = `qrcode-${Date.now()}.svg`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}
/** 复制分享链接 */
const handleCopy = async () => {
    try {
        await navigator.clipboard.writeText(shareUrl.value);
        ElMessage.success('复制成功');
    } catch (err) {
        ElMessage.error('复制失败，请手动选择复制');
    }
}
// 新增分类映射关系
const categoryMap = {
    images: '产品实物图',
    effectDrawing: '产品效果图',
    max: '产品模型MAX格式',
    step: '产品模型step格式',
    specification: '产品说明书',
    config: '产品配置参数表',
    promotionalVideo: '产品宣传视频',
    demonstrationVideo: '产品操作演示视频',
};

// 分类展示计算属性
const selectedFilesByCategory = computed(() => {
    const result = {};
    ['images', 'effectDrawing', 'max', 'step', 'specification', 'config', 'promotionalVideo', 'demonstrationVideo'].forEach(category => {
        const files = productInfo.value.fileCategories?.[category] || [];
        // 增加分类类型验证：同时匹配文件名和文件类型
        result[category] = files.filter(file =>
            selectedImages.value.includes(file.fileName) &&
            file.productType === category
        );
    });
    return Object.fromEntries(
        Object.entries(result).filter(([_, files]) => files.length > 0)
    );
});

// 修改后的分享处理函数
const handleShare = async () => {
    //调用接口保存数据，保存成功后弹框显示一个访问地址和一个二维码，该二维码包含这个访问地址，用户扫码后即可访问
    const selectedFiles = [];
    // 遍历所有分类的选中文件
    Object.values(selectedFilesByCategory.value).forEach(files => {
        files.forEach(file => {
            selectedFiles.push({
                productsFileId: file.productsFileId, // 携带文件唯一ID
                name: file.fileName,
                productId: file.productId
            })
        })
    });
    const params = {
        productsFileList: selectedFiles // 逗号分隔的文件ID
    };
    const res = await addProductsShare(params);
    if (res.code === 200) {
        ElMessage.success('分享成功');
        showShareTable.value = false;
        shareUrl.value = res.data.shareUrl;
        // 清空已选文件
        selectedImages.value = [];
        showShareTable.value = true;
    } else {
        ElMessage.error(res.msg || '分享失败');
    }
}

/********************操作按钮区***************************** */
function delFile() {
    if (selectedImages.value.length === 0) {
        ElMessage.error('请选择要删除的文件');
        return;
    }
    ElMessageBox.confirm('确定删除选中的文件吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: (action) => {
            //调用接口保存数据，保存成功后弹框显示一个访问地址和一个二维码，该二维码包含这个访问地址，用户扫码后即可访问
            const selectedFiles = [];
            // 遍历所有分类的选中文件
            Object.values(selectedFilesByCategory.value).forEach(files => {
                files.forEach(file => {
                    selectedFiles.push({
                        productsFileId: file.productsFileId, // 携带文件唯一ID
                        fileName: file.fileName,
                        productId: file.productId
                    })
                })
            });
            delProductFiles(selectedFiles).then(res => {
                console.log(res)
                //刷新附件列表
                getProductFileList();
                delDisabled.value = true;

            });
            console.log(selectedFiles)

        },
    })
}
function uploadProductFile(row) {
    uploadProduct.value.productName = row.name;
    uploadProduct.value.productId = row.productId;
    uploadProduct.value.open = true;
}
const uploadProduct = ref({
    open: false,
    title: '上传文件',
    productName: '',
    productId: null,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/system/products/uploadFile"
})
/******************************新增操作******************** */
const data = reactive({
    form: {
        categoryId: undefined, // 添加分类ID字段
        name: undefined,
        description: undefined
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        categoryId: undefined,
        delFlag: "0"
    },
    rules: {
        name: [{ required: true, message: "产品名称不能为空", trigger: "blur" }, { min: 2, max: 40, message: "产品名称长度必须介于 2 和 40 之间", trigger: "blur" }],
    }
});

const { queryParams, form, rules } = toRefs(data);
/** 新增按钮操作 */
function handleAdd() {
    reset();
    console.log(currentNode.value)
    if (!currentNode.value) {
        ElMessage.error('请先选择树节点')
        return
    }
    open.value = true;

};

/** 查询用户列表 */
function getList() {
    loading.value = true;
    listProducts(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
        loading.value = false;
        userList.value = res.rows;
        total.value = res.total;
    });
};
/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    title.value = "修改用户";
    open.value = true;
    form.value = { ...row };
};
/** 删除按钮操作 */
function handleDelete(row) {
    console.log(row);
    const productIds = row.productId || ids.value;
    proxy.$modal.confirm('是否确认删除产品编号为"' + productIds + '"的数据项？').then(function () {
        return delProducts(productIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
};
//查看附件
function queryFile(row) {
    currentProductId.value = row.productId;
    productInfoOpen.value = true;
    getProductFileList();
}
function getProductFileList() {
    getProducts(currentProductId.value).then(res => {
        if (res.code == 200) {
            productInfo.value = res.data
            // 使用精确分类字段
            productInfo.value.fileCategories = {
                images: res.data.productsFileList.filter(f => f.productType === 'images'),
                effectDrawing: res.data.productsFileList.filter(f => f.productType === 'effectDrawing'),
                max: res.data.productsFileList.filter(f => f.productType === 'max'),
                step: res.data.productsFileList.filter(f => f.productType === 'step'),
                specification: res.data.productsFileList.filter(f => f.productType === 'specification'),
                config: res.data.productsFileList.filter(f => f.productType === 'config'),
                promotionalVideo: res.data.productsFileList.filter(f => f.productType === 'promotionalVideo'),
                demonstrationVideo: res.data.productsFileList.filter(f => f.productType === 'demonstrationVideo')
            }
            // 新增：设置默认展开所有文件分类
            activeCollapseNames.value = Object.keys(productInfo.value.fileCategories)
                .filter(category => productInfo.value.fileCategories[category].length > 0)

        }
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["userRef"].validate(valid => {
        if (valid) {

            if (form.value.productId != undefined) {
                updateProducts(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                form.value.categoryId = currentNode.value.id;
                // 添加分类ID参数校验
                if (!form.value.categoryId) {
                    proxy.$modal.msgError("请选择分类节点");
                    return;
                }
                addProducts(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
};


/*******************************节点操作******************* */
const deptName = ref("");
const deptOptions = ref(undefined);
const contextMenuVisible = ref(false)
const contextMenuLeft = ref(0)
const contextMenuTop = ref(0)
const parentId = ref(0)
let currentNode = ref(null)


/** 节点单击事件 */
function handleNodeClick(data) {
    queryParams.value.categoryId = data.id;
    currentNode.value = data;
    form.value.categoryId = data.id;
    handleQuery();
};
/** 新增按钮操作 */
// function handleAdd() {
// reset();
// console.log(currentNode.value)
// if (!currentNode.value) {
//     ElMessage.error('请先选择树节点')
//     return
// }
// uploadProduct.value.open = true;

// };
//节点图标预览
const imageViewerVisible = ref(false)
const previewImgList = ref([]) // Initialize as array
const previewIndex = ref(0);  // 新增预览索引

const handleImagePreview = (index) => {
    previewIndex.value = index
    previewImgList.value = productInfo.value.fileCategories?.images.map(img => img.fileUrl) || []
    imageViewerVisible.value = true
};

// 新增选中状态管理
const selectedImages = ref([]) // 存储选中的图片索引

// 处理复选框变化
const handleCheckboxChange = (val) => {
    console.log('当前选中项:', selectedImages.value)
    delDisabled.value = selectedImages.value.length === 0; // 动态更新删除按钮禁用状态
}


//上传文件
const uploadFile = () => {
    upload.open = true
    upload.title = '上传文件'
}
// 右键菜单点击事件处理
const handleNodeContextmenu = (event, data, node) => {
    console.log('右键点击节点', node.data)
    parentId.value = node.data.id
    event.preventDefault()
    currentNode.value = node
    contextMenuLeft.value = event.clientX
    contextMenuTop.value = event.clientY
    contextMenuVisible.value = true
}

//新增顶级节点
const addTopLevel = () => {
    ElMessageBox.prompt('请输入节点名称', '新增顶级节点', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValidator: (value) => {
            if (!value?.trim()) return '名称不能为空'
        }
    }).then(({ value }) => {
        addCategories({ categoryName: value, parentId: 0 }).then(res => {
            console.log(res)
            if (res.code == 200) {
                ElNotification.success('添加成功')
                getDeptTree();
            }
        })
    }).catch(() => { })

    contextMenuVisible.value = false
}
// 删除节点
const deleteNode = () => {
    console.log(currentNode.value)
    delCategories(currentNode.value.data.id).then(res => {
        if (res.code == 200) {
            ElNotification.success('删除成功')
            // 重新加载树结构
            getDeptTree();
        }
    })
}
// 修改名称
const renameNode = () => {
    console.log(currentNode.value)
    if (!currentNode.value?.data) {  // 添加data存在性检查
        ElNotification.error('未找到节点数据')
        return
    }

    ElMessageBox.prompt('请输入新名称', '修改名称', {
        inputValue: currentNode.value.data.label,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValidator: (value) => {
            if (!value?.trim()) return '名称不能为空'
        }
    }).then(({ value }) => {
        updateCategories({ categoryId: currentNode.value.data.id, categoryName: value.trim() }).then(res => {
            if(res.code == 200){
                ElNotification.success('修改成功');
                getDeptTree();
            }
        })
    }).catch(() => { })
    contextMenuVisible.value = false
}
// 增加子节点
const addSubNode = () => {
    ElMessageBox.prompt('请输入子节点名称', '新增子节点', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValidator: (value) => {
            if (!value?.trim()) return '名称不能为空'
        }
    }).then(({ value }) => {
        if (currentNode.value) {
            addCategories({ categoryName: value, parentId: parentId.value }).then(res => {
                console.log(res)
                if (res.code == 200) {
                    ElNotification.success('添加成功')
                    getDeptTree();
                }
            })
        }
    }).catch(() => { })
    contextMenuVisible.value = false
}

// 添加点击外部关闭菜单的监听
document.addEventListener('click', () => {
    contextMenuVisible.value = false
})
/*** 用户导入参数 */
const upload = reactive({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});



/** 通过条件过滤节点  */
const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选部门树 */
watch(deptName, val => {
    proxy.$refs["deptTreeRef"].filter(val);
});



/** 查询部门下拉树结构 */
function getDeptTree() {
    categoryTreeSelect().then(response => {
        deptOptions.value = response.data;
        enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
    });
};

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
    return deptList.filter(dept => {
        if (dept.disabled) {
            return false;
        }
        if (dept.children && dept.children.length) {
            dept.children = filterDisabledDept(dept.children);
        }
        return true;
    });
};



/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
};

/** 重置按钮操作 */
function resetQuery() {
    dateRange.value = [];
    proxy.resetForm("queryRef");
    queryParams.value.deptId = undefined;
    proxy.$refs.deptTreeRef.setCurrentKey(null);
    handleQuery();
};


/** 选择条数  */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.productId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
};

/** 下载模板操作 */
function importTemplate() {
    proxy.download("system/user/importTemplate", {
    }, `user_template_${new Date().getTime()}.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false;
    upload.isUploading = false;
    proxy.$refs["uploadRef"].handleRemove(file);
    ElNotification({
        title: '附件上传结果',
        dangerouslyUseHTMLString: true,
        message: "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>" + "</br>" + file.name
    })
};

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit();
};

/** 重置操作表单 */
function reset() {
    form.value = {
        productId: undefined,
        name: undefined,
        description: undefined,
    };
    proxy.resetForm("userRef");
};

/** 取消按钮 */
function cancel() {
    open.value = false;
    reset();
};







getDeptTree();
getList();


</script>

<style lang="scss" scoped>
@import './css/index.scss'
</style>
